package com.igeek.ch02.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author
 * 2023/7/26 16:29
 * @description 登录过滤器
 */
//@WebFilter 标记当前类是过滤器  filterName属性：名字  urlPatterns属性：过滤路径
@WebFilter(filterName = "f2" , urlPatterns = {"/jsp/*","/success.jsp"})
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    //真正过滤逻辑
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        HttpSession session = request.getSession();

        Object user = session.getAttribute("sessionUser");
        if(user==null){
            response.sendRedirect("/login.jsp");
            return;
        }

        //放行
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}
